package com.ysx.server.service.impl;
import com.google.common.collect.Lists;

import com.ysx.server.mapper.MessageMapper;
import com.ysx.server.mapper.MessageParentMapper;
import com.ysx.server.mapper.UserMapper;
import com.ysx.server.pojo.dto.MessageDTO;
import com.ysx.server.pojo.entity.Message;
import com.ysx.server.pojo.entity.MessageParent;
import com.ysx.server.pojo.entity.OrderDetail;
import com.ysx.server.pojo.entity.User;
import com.ysx.server.pojo.vo.MessageVO;
import com.ysx.server.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageParentMapper messageParentMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 保存留言信息
     *
     * @param messageDTO
     */
    @Override
    public void save(MessageDTO messageDTO) {
        MessageParent messageParent=messageParentMapper.getByIdAndUser(messageDTO.getGoodsId(),messageDTO.getCreateName());
        Message message = new Message();
        message.setSendName(messageDTO.getSendName());
        message.setReceiveName(messageDTO.getReceiveName());
        message.setMessage(messageDTO.getMessage());
        message.setParentId(messageParent.getId());
        messageMapper.save(message);
        messageParentMapper.updateStatusNoOK(messageParent.getId());
    }

    /**
     * 得到留言信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<MessageVO> getMsg(Long userId) {
        User user = userMapper.getById(userId);
        List<Message> messages=messageMapper.getByUser(user.getUserAccount());
        Map<Long, List<Message>> parentIdsMap = messages.stream().collect(Collectors.groupingBy(Message::getParentId));
        List<MessageVO> messageVOS = new ArrayList<>();
        for(Long parentId:parentIdsMap.keySet()){
            MessageParent messageParent=messageParentMapper.getById(parentId);
            MessageVO messageVO = new MessageVO();
            messageVO.setId(messageParent.getId());
            messageVO.setGoodsId(messageParent.getGoodsId());
            messageVO.setGoodsName(messageParent.getGoodsName());
            messageVO.setCreateName(messageParent.getCreateName());
            messageVO.setMsgStatus(messageParent.getMsgStatus());
            List<Message> message = parentIdsMap.get(parentId).stream().sorted(Comparator.comparing(Message::getCreateTime)).toList();
            messageVO.setChildMessage(message);
            messageVOS.add(messageVO);
        }
        return messageVOS;
    }
}
